﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.DomainServices.Server.ApplicationServices;
using System.ServiceModel.DomainServices.Hosting;
using Scoreboard.Model;
using Scoreboard.Model.Authentication;

namespace Scoreboard.Model.Services
{
	[EnableClientAccess]
	public class AuthenticationService : AuthenticationBase<ScoreboardUser>
	{
		private static object _syncRoot = new object();

		protected override ScoreboardUser GetAuthenticatedUser(System.Security.Principal.IPrincipal principal)
		{
			lock (_syncRoot)
			{
				var scoreboardUser = base.GetAuthenticatedUser(principal);

				var container = new EntitiesContainer();
				var user = container.Users.Where(u => u.Login == scoreboardUser.Name).FirstOrDefault();

				if (user == null)
				{
					user = ExternalUserDataContainer.Current.GetUser(scoreboardUser.Name);
					if (user == null)
					{
						return scoreboardUser;
					}

					user.RatingValue = RatingEvaluator.RatingStartValue;

					container.AddToUsers(user);
					container.SaveChanges();
				}

				scoreboardUser.IsRegistered = true;
				scoreboardUser.FriendlyName = user.FriendlyName;

				return scoreboardUser;
			}
		}
	}
}